/**
 * 
 */
package com.star.csv;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: CsvUtil
 * @Description: TODO
 * @author starhq
 * @createtime 2014年10月28日 下午5:33:04
 * @email : jian.wang@shinsoft.net
 * @modify by TODO
 * @resaon
 * @edittime
 * @version 1.0
 * @copyright shinsoft
 */
public class CsvUtil {

	private static Logger logger = LoggerFactory.getLogger(CsvUtil.class);

	private static final String Separator = ",";

	/**
	 * 将结果集存储为CSV文件
	 * 
	 * @param rs
	 *            结果集
	 * @param pathWithName
	 *            要存储到文件的路径
	 */
	public static void toCsv(ResultSet rs, String pathWithName, String charset) {
		try {
			while (rs.next()) {
				int count = rs.getMetaData().getColumnCount();

				StringBuffer sb = new StringBuffer();
				for (int i = 1; i <= count; i++) {
					sb.append(rs.getObject(i));
					if (i == count)
						break;
					sb.append(Separator);
				}
				String line = sb.toString();
				logger.debug("写入:" + line);
				FileUtils.writeStringToFile(new File(pathWithName), line, true);
			}
		} catch (SQLException | IOException e) {
			logger.error("rs to csv error: {}", e.getMessage());
		}
	}

	/**
	 * 将集合中的内容写入CSV文件
	 * 
	 * @param collection
	 *            要写入文件的集合集合
	 * @param pathWithName
	 *            CSV文件路径，带文件名
	 * @param charset
	 *            字符集
	 */
	public static void toCSV(Collection<String> collection,
			String pathWithName, String charset) {
		try {
			for (String line : collection) {
				logger.debug("写入：" + line);
				FileUtils.writeStringToFile(new File(pathWithName), line, true);
			}
		} catch (IOException e) {
			logger.error("collectoin to csv error: {}", e);
		}
	}

}
